package com.shoping.common.health;

import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;

public class SpringHealthIndicator extends AbstractHealthIndicator {

    private Status status = Status.UNKNOWN;

    private Status initStatus = Status.UP;

    private static final Status PREPARED = new Status("PREPARED");

    private static final Status STARTING = new Status("STARTING");

    private static final Status STARTED = new Status("STARTED");

    private static final Status READY = new Status("READY");

    public SpringHealthIndicator(String is) {
        if (is == null || is.isEmpty()
                || is.equals("-")
                || is.equalsIgnoreCase(Status.UP.getCode())
                || is.equals("1")
        ) {
            return;
        }

        if (is.equalsIgnoreCase(Status.DOWN.getCode()) || is.equals("0")) {
            initStatus = Status.DOWN;
        } else if (is.equalsIgnoreCase(Status.OUT_OF_SERVICE.getCode()) || is.equals("-1")) {
            initStatus = Status.OUT_OF_SERVICE;
        } else if (is.equalsIgnoreCase(Status.UNKNOWN.getCode())) {
            initStatus = Status.UNKNOWN;
        } else {
            initStatus = new Status(is);
        }
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {
        if (status.equals(Status.UP)) {
            builder.up();
        } else {
            builder.down();
        }
        builder.withDetail("initStatus", initStatus.getCode());
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public Status getStatus() {
        return status;
    }

    protected void ready() {
        if (initStatus.equals(Status.UP)) {
            this.status = Status.UP;
        } else {
            this.status = READY;
        }
    }

    protected void prepared() {
        this.status = PREPARED;
    }

    protected void started() {
        this.status = STARTED;
    }

    protected void starting() {
        this.status = STARTING;
    }

    protected void down() {
        this.status = Status.DOWN;
    }
}
